package com.ruoyi.system.controller;


import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.send.SendUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.utils.uuid.VerificationCode;
import com.ruoyi.system.domain.Tribe;
import com.ruoyi.system.service.ITribeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;

@ConfigurationProperties(prefix = "spring")
@RestController
@RequestMapping("/send")
public class SysSendController {


    @Autowired
    ITribeService tribeService;

    @Value("${spring.mail.username}")
    private String sendMail;

    @Autowired
    RedisTemplate<String,String> redisTemplate;

    @GetMapping("/tribeSend")
    public AjaxResult tribeSend(@RequestParam(value = "number",required = false)String number){

        if(StringUtils.isEmpty(number)){
            return AjaxResult.error("部落编号不能为空");
        }
        List<Tribe> list=tribeService.selectTribeByNumber(number);
        if(list.size()==0) {
            return AjaxResult.error("该部落不存在!");
        }
        String s = redisTemplate.boundValueOps("tribe::" + number + "::" + "count").get();
        if (!StringUtils.isEmpty(s)){
            return AjaxResult.error("60s内不能重新获取!");
        }
        try {
            String letter = VerificationCode.getLetter(5);
            SendUtils.sendHtmlEmail(sendMail,list.get(0).getEmail(),"部落邮箱验证码",letter);
            //将验证码放入redis里
            redisTemplate.boundValueOps("tribe::"+number).set(letter,60*5,TimeUnit.SECONDS);
            //开始计时
            redisTemplate.boundValueOps("tribe::"+number+"::"+"count").set(letter,1,TimeUnit.MINUTES);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("服务器发送出错,请稍后再试!");
        }
        return AjaxResult.success("短信已发送,请注意查收!");
    }
}
